import Vue from 'vue'
import Vuex from 'vuex'
import module from './module'
import createLogger from 'vuex/logger'

Vue.use(Vuex)

const localStorage = {
  onInit (state, store) {
    console.debug('[vuex] load state.user from localStorage')
    try {
      _.assign(state.user.me, JSON.parse(window.localStorage.getItem('me')))
    } catch (e) {
      console.error(e)
    }
  },
  onMutation (mutation, state, store) {
    if ( ['LOG_IN', 'LOG_OUT'].includes(mutation.type) ) {
      console.debug('[vuex] save state.user to localStorage')
      window.localStorage.setItem('me', JSON.stringify(state.user.me))
    }
  }
}

export default new Vuex.Store({
  modules: module,
  strict: process.env.DEBUG_MODE,
  middlewares: [localStorage].concat(process.env.DEBUG_MODE ? createLogger() : [])
})
